#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <dirent.h>
#include "cJSON/cJSON.h"
#include "cgic.h"

int cgiMain()
{
    struct dirent *entry;
    struct dirent **entryList;
    int size;
    char name[32] = {0};

    FILE *file = fopen("/demo/bin/boa/www/cjson_dir/network_detail.json", "r");
    if (file == NULL)
    {
        perror("打开文件时出错");
        return EXIT_FAILURE;
    }
    fseek(file, 0, SEEK_END);
    long length = ftell(file);
    fseek(file, 0, SEEK_SET);
    char *data = (char *)malloc(length + 1);
    fread(data, 1, length, file);
    data[length] = '\0';

    cJSON *json = cJSON_Parse(data);
    if (json == NULL)
    {
        const char *error_ptr = cJSON_GetErrorPtr();
        if (error_ptr != NULL)
        {
            fprintf(stderr, "错误前：%s\n", error_ptr);
        }
        cJSON_Delete(json);
        free(data);
        return -1;
    }

    cgiHeaderContentType("text/html");
    fprintf(cgiOut, "<HTML><HEAD>\n");
    fprintf(cgiOut, "<TITLE>FFMPEG_List Manage</TITLE></HEAD>\n");
    fprintf(cgiOut, "<BODY>");

    fprintf(cgiOut, "<br>");
    cJSON *url_address_json = cJSON_GetObjectItem(json,"url_address");
    char *network_address = url_address_json->valuestring;
    fprintf(cgiOut, "<H3>%s</H3>", network_address);
    fprintf(cgiOut, "</br>");
#if 0
    for (int i = 0; i < size; i++)
    {
        entry = entryList[i];
        memset(name, 0, sizeof(name));
        strcpy(name, entry->d_name);
        fprintf(cgiOut, "<br>");
        fprintf(cgiOut, "<img src=/www/Image/%s width=100 height=200>\n", name);
        fprintf(cgiOut, "</br>");
        fprintf(cgiOut, "<br>");
        fprintf(cgiOut, "<H3>%s</H3>", name);
        fprintf(cgiOut, "</br>");
    }
#endif
    //fprintf(cgiOut, "<a href=\"/takePhoto.html\">TakePhoto</a>\n");
    //fprintf(cgiOut, "<a href=\"/index.html\">Index</a>\n");
    fprintf(cgiOut, "</BODY>\n");
    fprintf(cgiOut, "</HTML>\n");
    return 0;
}
